package com.xindaoapp.happypet.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.DiscCacheAware;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.view.picture.SelectImgEdit;

/**
 * 图片查看类（帖子内容跳转过来）
 * 
 * @author chenghao
 * 
 */
public class PostImageActivity extends UMBaseActivity {
    private SelectImgEdit window;

    // private Context mContext;
    private ViewPager mViewpager;
    private TextView vp_size;
    private TextView vp_total;

    private LinearLayout number;

    private int current = -1;
    private ArrayList<String> list = new ArrayList<String>();

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    number.setVisibility(View.GONE);
                    break;
                default:
                    break;
            }
        };
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_post_image);
        window = new SelectImgEdit(PostImageActivity.this, itemsOnClick);
        // mContext = PostImageActivity.this;
        number = (LinearLayout) findViewById(R.id.number);
        current = getIntent().getIntExtra(Constants.KEY_CURRENT_INDEX, -1);
        list = getIntent().getStringArrayListExtra(Constants.KEY_PHOTOS);

        if (!file.exists()) {
            file.mkdir();
        }

        initView();
        initData();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                number.setVisibility(View.GONE);
            }
        }, 5000);
    }

    private void initView() {
        mViewpager = (ViewPager) findViewById(R.id.viewpager);
        vp_size = (TextView) findViewById(R.id.product_detail_size);
        vp_total = (TextView) findViewById(R.id.product_detail_size_total);
    }

    private void initData() {
        prepareViewPage();
    }

    public void prepareViewPage() {
        ViewPagerAdapter adapter = new ViewPagerAdapter();
        mViewpager.setAdapter(adapter);
        mViewpager.setCurrentItem(current);
        mViewpager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(final int position) {
                vp_size.setText(position + 1 + "");
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                number.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        number.setVisibility(View.GONE);
                    }
                }, 5000);
            }
        });
        Log.e("---->", current + 1 + "");
        vp_size.setText(current + 1 + "");
        vp_total.setText("/" + list.size());
    }

    class ViewPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        /**
         * 判断出去的view是否等于进来的view 如果为true直接复用
         */
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        /**
         * 销毁预加载以外的view对象, 会把需要销毁的对象的索引位置传进来就是position
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        /**
         * 创建一个view
         */
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            // final GestureImageView iv = new GestureImageView(mContext);
            View view = View.inflate(getBaseContext(), R.layout.item_post_detail_image, null);
            ImageView iv = (ImageView) view.findViewById(R.id.icon);
            imageurl = list.get(position);
            if (CommonParameter.isLoadImg) {
                ImageLoader.getInstance().displayImage(imageurl, iv);
            } else {
                iv.setImageResource(R.drawable.picture_loading);
            }
            iv.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    CommonUtil.addScreenBg(window, PostImageActivity.this);
                    window.showAtLocation(
                            PostImageActivity.this.findViewById(R.id.activity_post_image),
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                    return false;
                }

            });
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            container.addView(view);
            return view;
        }
    }

    private String imageurl;
    private final File file = new File(Environment.getExternalStorageDirectory(), "happypet/image");
    private final OnClickListener itemsOnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_share:
                    Toast.makeText(getApplicationContext(), "分享", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.btn_location:
                    final DiscCacheAware discCache = ImageLoader.getInstance().getDiscCache();
                    File myCaptureFile = new File(file, System.currentTimeMillis() + ".png");
                    try {
                        BufferedOutputStream bos =
                                new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                        File bmp = discCache.get(imageurl);
                        FileInputStream in = new FileInputStream(bmp);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = in.read(buf)) != -1) {
                            bos.write(buf, 0, len);
                        }
                        bos.flush();
                        bos.close();
                        in.close();
                        Toast.makeText(getApplicationContext(),
                                "图片保存至" + myCaptureFile.getAbsolutePath(), Toast.LENGTH_SHORT)
                                .show();
                        finish();
                    } catch (FileNotFoundException e) {
                        Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    } catch (IOException e) {
                        Toast.makeText(getApplicationContext(), "保存失败", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

}
